import axios from 'axios';
import Qs from 'qs';
import { urlConfig } from 'libs/config';
import { message } from 'antd';
import { Dialog } from 'components'

//axios实例，包含默认配置
const instance = axios.create({
  baseURL: urlConfig.baseUrl,
  withCredentials: true,
  headers: {
    'Cache-Control': 'no-cache'
  }
});

const getTimestamp = () => {
  return `t=${new Date().getTime()}`
}

//接口请求成功的回调
const successCallback = (res, resolve, reject, showErrorNotice) => {
  // 成功
  if (res.data.code === 1) {
    resolve(res.data);
  }
  // 失败
  else if(res.data.code === 2) {
    reject(res.data)
    showErrorNotice && Dialog({message: res.data.msg})//_alert(res.data.msg)
  }
  // 登陆过期，清空token、cokie
  else if (res.data.code === 3) {
    // 地址栏中含有这些路由的不验证登录
    // const reg = new RegExp(`
    //   #\/home|
    //   #\/long_english|
    //   #\/long_program|
    //   #\/long_english_pad|
    //   #\/long_program_pad
    // `)
    const other = /(#\/home|#\/student\/password_login|#\/student\/sms_login|#\/student\/register|#\/student\/agreement|\/long_english|\/long_program|\/long_english_pad|\/long_program_pad)/.test(window.location.href)
    if(!other) {
      reject('登录失效，请重新登录');
      showErrorNotice && message.warning(res.data.msg, 4)
      window.location.href = '/'
    }
  // 不需要设置密码，注册时已经添加密码
  // }else if (res.data.code === 5) {
  //   // 初次登陆还未设置密码
  //   console.log('初次登陆，请设置密码')
  //   resolve(res.data)
  //   window.location.href = '/#/student_center/personal_center/layout/edit_password'
  }
  else {
    reject(res.data);
    showErrorNotice && message.warning(res.data.msg, 4)
  }
}

//接口请求失败的回调
const failureCallback = (err, reject) => {
  reject(err);
}

export default {
  get: (url, params = {}, config = {}, showErrorNotice=false) => {
    const data = {};
    const timestamp = /\?/.test(url) ? `&${getTimestamp()}` : `?${getTimestamp()}`
    for (let attr in params) {
      if (!(params[attr] && typeof params[attr] === 'object')) {
        data[`${attr}`] = params[attr];
      }
    }
    return new Promise((resolve, reject) => {
      instance
      .get(url + timestamp, { params: data, ...config })
      .then(res => successCallback(res, resolve, reject, showErrorNotice))
      .catch(err => failureCallback(err, reject));
    });
  },
  post: (url, params = {}, config = {}, showErrorNotice=false) => {
    // let data = {};
    url += `?${getTimestamp()}`
    // for (let attr in params) {
    //   data[`${attr}`] = params[attr];
    // }
    // data = Qs.stringify(data);
    return new Promise((resolve, reject) => {
      instance
      .post(url, Qs.stringify(params), config)
      .then(res => successCallback(res, resolve, reject, showErrorNotice))
      .catch(err => failureCallback(err, reject));
    });
  },
  json: (url, params = {}, config = {}, showErrorNotice=false) => {
    let data = { param: params };
    url += `?${getTimestamp()}`
    return new Promise((resolve, reject) => {
      instance
      .post(url, data, config)
      .then(res => successCallback(res, resolve, reject, showErrorNotice))
      .catch(err => failureCallback(err, reject));
    });
  },
  upload: (url, params = {}, config = {}, showErrorNotice=false) => {
    let data = params;
    config = Object.assign({}, config, {
      "Accept": "*/*",
      "Content-Type": "application/x-www-form-urlencoded",
      "X-Requested-With": "XMLHttpRequest"
    })
    return new Promise((resolve, reject) => {
      instance
      .post(url, data, config)
      .then(res => successCallback(res, resolve, reject, showErrorNotice))
      .catch(err => failureCallback(err, reject));
    });
  }
}
